package web.controller;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {

    //设置上传文档的路径
    public static final String URL="D:\\upload\\";
    //返回数据的方式必须是json格式
    public static final String RESPONSE="{\n" +
            "  \"code\": 0\n" +
            "  ,\"msg\": \"\"\n" +
            "  ,\"data\": {\n" +
            "    \"src\": \"XXX\"\n" +
            "  }\n" +
            "} ";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入了doPost方法");
        //1.创建文件上传对象
        ServletFileUpload upload = new ServletFileUpload();
        //获取到迭代器
        try {
            FileItemIterator itemIterator = upload.getItemIterator(req);
            while (itemIterator.hasNext()){
                //获取到每一个字段
                FileItemStream next = itemIterator.next();
                //判断是否是文件
                if(next.isFormField()){ //是则是普通字段
                    System.out.println(next.getFieldName()+"---"+ Streams.asString(next.openStream()));
                }else{
                    System.out.println("我进来了");
                    String name = next.getName();
                    name = UUID.randomUUID().toString().replace("-", "").substring(0, 12)+
                            //subString方法时截取操作  name.lastIndexOf(".")表示最后一个.出现的位置
                            name.substring(name.lastIndexOf("."));
                    //保存到上传目录
                    Streams.copy(next.openStream(),new FileOutputStream(URL+name),true);
                    //返回结果给前端
                    resp.getWriter().write(RESPONSE.replace("XXX",name));
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}
